// 所有ajax请求应该引入此类，这样可以全局进行过滤，单独引入不保证axios配置生效
import axios from 'axios'
import {isDemo, isProd, isQa, isServer} from './env-process'
import {admin_auth_cookie_key, deleteCookie, getCookie} from './cookie-process.js'

axios.defaults.withCredentials = false // 不要开启，开启的话会有跨域问题，需要配置。我们设置header传输即可，无需传递cookie

//注意：如果正式环境https，可以设置内部服务域名（负载均衡或者k8s的service），避免https跨域或者服务器不开通对外访问权限的问题
export const getRootApi = function (urlRoot) {
  let apiRoot = 'http://localhost:9001' //本地后台接口地址
  if (isQa()) {
    apiRoot = isServer() ? 'http://10.180.20.11:9001' : 'http://localhost:9001'
  }
  if (isDemo()) {
    apiRoot = isServer() ? '' : ''
  }
  if (isProd()) {
    apiRoot = isServer() ? '' : ''
  }
  if (urlRoot) {
    apiRoot = apiRoot + urlRoot
  }
  return apiRoot
}

//与上同理，用于websocket连接
// export const getWsRootApi = function (urlRoot) {
//   let apiRoot = 'ws://localhost:9099'
//   if (process.env.NODE_ENV === 'production') {
//     if (process.env.VUE_APP_ENV === 'qa') {
//       apiRoot = 'ws://xxxx.com'
//     } else if (process.env.VUE_APP_ENV === 'demo') {
//       apiRoot = ''
//     } else {
//       apiRoot = ''
//     }
//   }
//   if (urlRoot) {
//     apiRoot = apiRoot + urlRoot
//   }
//   return apiRoot
// }

export default (ctx, router) => {
  let ajax = axios.create({})

  //获取rest api相关
  function getRestPromise(url, params, method) {
    return new Promise((resolve, reject) => {
      ajax[method](getRootApi(url), params).then(response => {
        resolve(response.data)
      }).catch(err => {
        reject(err)
      })
    })
  }

  // 请求之前,可以封装header，将token放入header中传递，具体根据鉴权方式自己设定
  ajax.interceptors.request.use(request => {
    let auth_header = getCookie(ctx, admin_auth_cookie_key)
    console.log(request.method, request.url, request.params, process.env.NODE_ENV, process.env.VUE_APP_ENV, auth_header)
    if (auth_header) {
      request.headers[admin_auth_cookie_key] = auth_header
    }
    //console.log(request.headers)
    return request
  }, err => {
    return Promise.reject(err)
  })

  ajax.interceptors.response.use(response => {
    console.log(response.data)
    return response
  }, err => {
    console.error(err)
    goLogin(err && err.response && err.response.data ? err.response.data.code : 0)
    return Promise.reject(err)
  })

//这里可以根据返回值确定是否需要重新登录
  function goLogin(code) {
    // after
    if (code === 403) {
      deleteCookie(ctx, admin_auth_cookie_key)
      router.$$redirect('/login')
    }
  }

  const get = function (url, params) {
    return getRestPromise(url, {params: params}, 'get')
  }
  const del = function (url, params) {
    return getRestPromise(url, {params: params}, 'delete')
  }
  const post = function (url, params) {
    return getRestPromise(url, params, 'post')
  }
  const put = function (url, params) {
    return getRestPromise(url, params, 'put')
  }

  return {
    ajax: ajax,
    get: get,
    del: del,
    post: post,
    put: put
  }
}